package cn.edu.xaut.servlet;

import cn.edu.xaut.bean.UserBean;
import cn.edu.xaut.db.ConnDB;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/manageInit")
public class ManageInit extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置字符编码
        response.setContentType("application/json;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        try {
            // 查询操作
            String sql = "select * from dbmis.tb_student";
            ResultSet rs = ConnDB.query(sql);

            // 将查询到的数据存放到集合对象，然后转发到manage.jsp
            List<UserBean> userList = new ArrayList<>();

            while (rs.next()) {

                UserBean ub = new UserBean();

                ub.setId(rs.getInt("id"));
                ub.setUsername(rs.getString("username"));
                ub.setPassword(rs.getString("password"));
                ub.setRealname(rs.getString("realname"));
                ub.setTel(rs.getString("tel"));
                ub.setEmail(rs.getString("email"));
                ub.setCollege(rs.getString("college"));
                ub.setRegisterDate(rs.getDate("registertime").toString());

                userList.add(ub);
            }

            // 将Java对象转换为Json字符串
            String json = JSON.toJSONString(userList);
            PrintWriter out = response.getWriter();
            out.println(json);

            ConnDB.close(); // 释放资源
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
